/**
 * 
 */
package com.jeedle.nahe;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.widget.MultiAutoCompleteTextView.Tokenizer;

/**
 * @author maximo
 *
 */
public class SpaceTokenizer implements Tokenizer {

	/* (non-Javadoc)
	 * @see android.widget.MultiAutoCompleteTextView.Tokenizer#findTokenStart(java.lang.CharSequence, int)
	 */
	@Override
	public int findTokenStart(CharSequence text, int cursor) {
		int i = cursor;
			
		while (i >0 && text.toString().replace('\n',' ').charAt(i -1) !=' ')
		{
			i--;
			
		}
		
		while (i < cursor && text.toString().replace('\n',' ').charAt(i) == ' ' )
		{
			i++;
		}
		return i;
	}

	/* (non-Javadoc)
	 * @see android.widget.MultiAutoCompleteTextView.Tokenizer#findTokenEnd(java.lang.CharSequence, int)
	 */
	@Override
	public int findTokenEnd(CharSequence text, int cursor) {
		int i = cursor;
		int len = text.length();
		
		while (i <len)
		{
			if (text.toString().replace('\n', ' ').charAt(i) == ' ')
			{
				return i;	
			}
			else 
			{
				i++;
			}
		}
		return 0;
	}

	/* (non-Javadoc)
	 * @see android.widget.MultiAutoCompleteTextView.Tokenizer#terminateToken(java.lang.CharSequence)
	 */
	@Override
	public CharSequence terminateToken(CharSequence text) {
		int i = text.length();
		
        while(i > 0 && text.toString().replace('\n',' ').charAt(i - 1) == ' ' )
        {
         i--;	
        }
        
        if (i > 0 && text.toString().replace('\n',' ').charAt(i -1) == ' ')
        {
        	return text;
        }
        else
        {
        	 if (text instanceof Spanned)
        	 {
        		 SpannableString sp = new SpannableString(text + "  ");
        		 sp.setSpan(new ForegroundColorSpan(Color.BLUE),0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        		 TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0);
        		 return sp;
        	 }
        	 else
        	 {
        		 return text + "  ";
        	 }
        }
		//return null;
	}

}
